package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.SearchResultAdapter;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.MySocket.RecDataCallBackListener_Serach;
import com.dotstone.chipism.dialog.OnDismissListener;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.dialog.SVProgressHUD.SVProgressHUDMaskType;
import com.dotstone.chipism.util.ConvertUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SearchDeviceActivity2 extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mTypeTv;
	private Button mNextstepB;
	private TextView mResultT;
	private ListView mResultLv;
	private SearchResultAdapter mAdapter;
	private TextView tv_statusBar_mian;
	private NormalDialog mNormalDialog;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private boolean searching = true;
	private int[] rfLight = new int[] { 1, 255, 255, 255, 255, 4, 67, 0, 0, 0 };
	private int[] rfLight2 = new int[] { 1, 255, 255, 255, 255, 16, 67, 0, 0, 0 };
	private int[] cwLight = new int[] { 1, 255, 255, 255, 255, 10, 67, 0, 0, 0 };
	private int[] rfswitch = new int[] { 1, 255, 255, 255, 255, 37, 67, 0, 0, 0 };
	private int[] cwSocket = new int[] { 1, 255, 255, 255, 255, 1, 67, 0, 0, 0 };
    private int[] cwCurtain = new int[] { 1,255,255,255,255,48,67,0,0,0 };//65
    private int[] wireless1 = new int[] { 1,85,170,90,27,73,82,51 };
	private int[] wireless_1 = new int[] { 1,255,255,255,255,73,67,0,0,0 };
	private int[] wireless_2 = new int[] { 1,255,255,255,255,74,67,0,0,0 };
	private int[] wireless_3 = new int[] { 1,255,255,255,255,75,67,0,0,0 };
	private int[] linghuo_switch_1 = new int[] { 1,255,255,255,255,97,67,0,0,0 };
	private int[] linghuo_switch_2 = new int[] { 1,255,255,255,255,98,67,0,0,0 };
	private int[] linghuo_switch_3 = new int[] { 1,255,255,255,255,99,67,0,0,0 };
	private int[] danhuo_switch_1 = new int[] { 1,255,255,255,255,100,67,0,0,0 };
	private int[] danhuo_switch_2 = new int[] { 1,255,255,255,255,101,67,0,0,0 };
	private int[] danhuo_switch_3 = new int[] { 1,255,255,255,255,102,67,0,0,0 };
	private int[] chazuo = new int[] { 1, 255, 255, 255, 255, 8, 67, 0, 0, 0 };
    private String searchCmd;
	public int type;
	private MySocket socket;
	private boolean isSearching = false;
	private String deviceAddress;
	private List<Device> mDeviceList = new ArrayList<Device>();
	private String deviceType;
	private SVProgressHUD mSVProgressHUD;
	private SVProgressHUD mSVProgressHUD1;
	private int mUpLoadCounts = 0;
	private int count = 0;
	private Button mSearchB;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			if (mDeviceList.size() == 0) {
				if (!searching) {
					socket.setNotReceiving(true);
					finish();
				} else {
					exit();
				}
			} else {
				exit1();
			}
			break;
		case R.id.nextstep:
			// 先检查名称是否重复 要在全部设备中检查，否则如果名字重复会导致设备无法控制
			if(searching){
				searching = false;
				mSearchB.setText("重新搜索");
			}
			mDeviceList = mAdapter.getData();
			saveLight1();
//			for (int i = 0; i < mDeviceList.size(); i++) {
//				mDeviceList.get(i).existed = false;
//			}
//			String temp = "";
//			boolean e1 = false;
//			for (int i = 0; i < mDeviceList.size() - 1; i++) {
//				temp = mDeviceList.get(i).getDeviceName();
//				if (temp.length() < 2) {
//					ToastShow.Show(getApplicationContext(), getString(R.string.device_name_not_vaild));
//					return;
//				}
//				for (int j = i + 1; j < mDeviceList.size(); j++) {
//					if (temp.equals(mDeviceList.get(j).getDeviceName())) {
//						Log.i("wmy", "第" + (i + 1) + "个跟第" + (j + 1) + "个重复，值是：" + temp);
//						mDeviceList.get(i).existed = true;
//						mDeviceList.get(j).existed = true;
//						e1 = true;
//					}
//				}
//
//			}
//
//			boolean rename = false;
//			for (int i = 0; i < mDeviceList.size(); i++) {
//				Log.i("wmy", "保存设备" + mDeviceList.get(i).getDeviceName());
//				boolean e = DeviceManager.getInstance().checkName(mDeviceList.get(i).getDeviceName());
//				if (e) {
//					rename = true;
//					mDeviceList.get(i).existed = true;
//				}
//			}
//			if (rename || e1) {
//				mAdapter.notifyDataSetChanged();
//				ToastShow.Show(getApplicationContext(), getString(R.string.device_exists2));
//				return;
//			} else {
//				// 再提交
//				for (int i = 0; i < mDeviceList.size(); i++) {
//					mDeviceList.get(i).existed = false;
//				}
//				mAdapter.notifyDataSetChanged();
//				saveLight1();
//			}
			break;
		case R.id.search:
			if(searching){
				searching = false;
//				stopSearch();
				mSearchB.setText("重新搜索");
			}else{
				searching = true;
				mSearchB.setText("停止搜索");
//				adjustConnectState();
				initData();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mDeviceList.size() == 0) {
				if (!searching) {
					socket.setNotReceiving(true);
					finish();
				} else {
					exit();
				}
			} else {
				exit1();
			}
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void exit() {
		mNormalDialog = new NormalDialog(SearchDeviceActivity2.this);
		mNormalDialog.content("您正在搜索智能家电设备，是否返回？").style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				searching = false;
				socket.setNotReceiving(true);
				finish();
			}

		});
	}

	private void exit1() {
		mNormalDialog = new NormalDialog(SearchDeviceActivity2.this);
		mNormalDialog.content("您有搜索到的智能家电设备尚未保存，是否返回？").style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}

		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				searching = false;
				socket.setNotReceiving(true);
				finish();
			}

		});
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				searching = false;
				mResultLv.setVisibility(View.VISIBLE);
				socket.setNotReceiving(true);
				socket.setSendHeartBeatTime(System.currentTimeMillis());
				socket.setReceiveHeartBeatTime(System.currentTimeMillis());
				if (mDeviceList.size() == 0) {
					mResultT.setText("共搜索到0个" + deviceType);
					Toast toast = Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.none_device_search), Toast.LENGTH_SHORT);
					toast.show();
				} else {
					mResultT.setText("共搜索到" + mDeviceList.size() + "个" + deviceType);
					mNextstepB.setVisibility(View.VISIBLE);
//					mAdapter = new SearchResultAdapter(getApplicationContext(), mDeviceList);
					mResultLv.setAdapter(mAdapter);
				}
				break;
			case 1:
				int count = msg.arg1;
				count++;
				if (count < mDeviceList.size()) {
					upLoadDevices(count);
				} else {
					Toast.makeText(getApplicationContext(), "设备绑定成功！", Toast.LENGTH_SHORT).show();
					mDeviceList.clear();
					AddTypeSelectionActivity.addTypeSelectionActivity.finish();
					AddDeviceTypeSelectionActivity.addDeviceTypeSelectionActivity.finish();
					socket.setNotReceiving(true);
					finish();
				}
				break;
			case 2:
				socket.setNotReceiving(true);
				finish();
				break;
			case 3:
				adjustConnectState();
				break;
			case 4:
				if (mDeviceList.size() == 0) {
					mResultT.setText("共搜索到0个" + deviceType);
					Toast toast = Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.none_device_search), Toast.LENGTH_SHORT);
					toast.show();
				} else {
					mResultT.setText("共搜索到" + mDeviceList.size() + "个" + deviceType);
					mNextstepB.setVisibility(View.VISIBLE);
					mAdapter.notifyDataSetChanged();
				}
				break;
			default:
				break;
			}
		}
	};

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_search_device;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mTypeTv = $(R.id.search_type_tv);
		mNextstepB = $(R.id.nextstep);
		mNextstepB.setText(getResources().getString(R.string.save));
		mResultT = $(R.id.result_tv);
		mResultLv = $(R.id.result_lv);
		mSearchB = $(R.id.search);
		mBackL.setOnClickListener(this);
		mNextstepB.setOnClickListener(this);
		mSearchB.setOnClickListener(this);
		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		// rippleBackground = $(R.id.content);
		mSVProgressHUD = new SVProgressHUD(SearchDeviceActivity2.this);
		mSVProgressHUD1 = new SVProgressHUD(SearchDeviceActivity2.this);
		mSVProgressHUD1.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss(SVProgressHUD hud) {
				// TODO Auto-generated method stub
//				if(){
					searching = false;
//					stopSearch();
					mSearchB.setText("重新搜索");
//				}
			}
		});
		mAdapter = new SearchResultAdapter(getApplicationContext(), mDeviceList);
		mResultLv.setAdapter(mAdapter);
		boolVersion();
		type = getIntent().getIntExtra("type", 0);
		switch (type) {
            case DeviceType.DEVICE_TYPE_SOCKET:
                mTypeTv.setText("搜索转接插座");
                deviceType = "转接插座";
                searchCmd = ConvertUtil.getInstance().convertSearchCmd(cwSocket);
                break;
            case DeviceType.DEVICE_TYPE_RGB_LIGHT:
                mTypeTv.setText("搜索智能彩灯");
                deviceType = "智能彩灯";
                searchCmd = ConvertUtil.getInstance().convertSearchCmd(rfLight);
                break;
            case DeviceType.DEVICE_TYPE_SW_LIGHT:
                mTypeTv.setText("搜索智能色温灯");
                deviceType = "智能色温灯";
                searchCmd = ConvertUtil.getInstance().convertSearchCmd(cwLight);
                break;
            case DeviceType.DEVICE_TYPE_SWITCH:
                mTypeTv.setText("搜索电源控制盒");
                deviceType = "智能电源控制盒";
                searchCmd = ConvertUtil.getInstance().convertSearchCmd(rfswitch);
                break;
            case DeviceType.DEVICE_TYPE_RGB_TIAO:
                mTypeTv.setText("搜索智能灯带");
                deviceType = "智能灯带";
                searchCmd = ConvertUtil.getInstance().convertSearchCmd(rfLight2);
                break;
            case DeviceType.DEVICE_TYPE_CURTAIN:
                mTypeTv.setText("搜索智能窗帘");
                deviceType = "智能窗帘";
                searchCmd = ConvertUtil.getInstance().convertSearchCmd(cwCurtain);
                break;
            case DeviceType.WIRELSEE_SWITCH_1:
                mTypeTv.setText("搜索无线开关(贴墙式1位)");
                deviceType = "无线开关(贴墙式1位)";
                searchCmd = ConvertUtil.getInstance().convertSearchCmd(wireless_1);
                break;
			case DeviceType.WIRELSEE_SWITCH_2:
				mTypeTv.setText("搜索无线开关(贴墙式2位)");
				deviceType = "无线开关(贴墙式2位)";
				searchCmd = ConvertUtil.getInstance().convertSearchCmd(wireless_2);
				break;
			case DeviceType.WIRELSEE_SWITCH_3:
				mTypeTv.setText("搜索无线开关(贴墙式3位)");
				deviceType = "无线开关(贴墙式3位)";
				searchCmd = ConvertUtil.getInstance().convertSearchCmd(wireless_3);
				break;
			case DeviceType.LINGHUO_SWITCH_1:
				mTypeTv.setText("搜索墙壁开关(零火1位)");
				deviceType = "墙壁开关(零火1位)";
				searchCmd = ConvertUtil.getInstance().convertSearchCmd(linghuo_switch_1);
				break;
			case DeviceType.LINGHUO_SWITCH_2:
				mTypeTv.setText("搜索墙壁开关(零火2位)");
				deviceType = "墙壁开关(零火2位)";
				searchCmd = ConvertUtil.getInstance().convertSearchCmd(linghuo_switch_2);
				break;
			case DeviceType.LINGHUO_SWITCH_3:
				mTypeTv.setText("搜索墙壁开关(零火3位)");
				deviceType = "墙壁开关(零火3位)";
				searchCmd = ConvertUtil.getInstance().convertSearchCmd(linghuo_switch_3);
				break;
			case DeviceType.DANHUO_SWITCH_1:
				mTypeTv.setText("搜索墙壁开关(单火1位)");
				deviceType = "墙壁开关(单火1位)";
				searchCmd = ConvertUtil.getInstance().convertSearchCmd(danhuo_switch_1);
				break;
			case DeviceType.DANHUO_SWITCH_2:
				mTypeTv.setText("搜索墙壁开关(单火2位)");
				deviceType = "墙壁开关(单火2位)";
				searchCmd = ConvertUtil.getInstance().convertSearchCmd(danhuo_switch_2);
				break;
			case DeviceType.DANHUO_SWITCH_3:
				mTypeTv.setText("搜索墙壁开关(单火3位)");
				deviceType = "墙壁开关(单火3位)";
				searchCmd = ConvertUtil.getInstance().convertSearchCmd(danhuo_switch_3);
				break;
			case DeviceType.DEVICE_TYPE_CHAZUO:
				mTypeTv.setText("搜索墙壁插座");
				deviceType = "墙壁插座";
				searchCmd = ConvertUtil.getInstance().convertSearchCmd(chazuo);
				break;
            default:
                break;
		}
		adjustConnectState();
	}

	private void adjustConnectState() {
		Log.i("wmy", "socket = " + DeviceManager.getInstance().getmWlanId());
		socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
		if (socket != null) {
			if (socket.isLocalSuccess()) {
				initData();
				// 设置回调
				setRecvListener();
			} else {
				// 有该socket 但是socket未连接
				ToastShow.Show(getApplicationContext(), "该网关暂未连接上局域网，无法搜索设备");
			}
		} else {
			ToastShow.Show(getApplicationContext(), getString(R.string.search_fail));
			Intent intent = new Intent(getApplicationContext(), WlanSelectionActivity.class);
			startActivity(intent);
			socket.setNotReceiving(true);
			finish();
		}
	}

	private void setRecvListener() {
		if (socket != null) {
			socket.setRecDataCallBackListener_Serach(new RecDataCallBackListener_Serach() {

				@Override
				public void onReceiveData(String data) {
					// TODO Auto-generated method stub
					if (isSearching) {
						// Log.i("wmy", "收到回调" + data);
						// 开始解析
						deviceAddress = parseData(data);
						Log.i("wmy", "得到设备地址" + deviceAddress);
						String deviceName = "";
						int deviceType = type;
						if ((deviceAddress.length() < 2)) {
							return;
						}
						if (type == DeviceType.DEVICE_TYPE_RGB_LIGHT) {// 彩灯
							deviceType=parseWireLessType(data);
							if(deviceType==12){
								deviceName = "彩灯" + deviceAddress.substring(0, 4);
							}else{
								return;
							}
						} else if (type == DeviceType.DEVICE_TYPE_RGB_TIAO) {// 彩灯
							deviceType=parseWireLessType(data);
							if(deviceType==18){
								deviceName = "彩条" + deviceAddress.substring(0, 4);
							}else{
								return;
							}
						} else if (type == DeviceType.DEVICE_TYPE_SW_LIGHT) {// cw
							deviceType=parseWireLessType(data);
							if(deviceType==15){
								deviceName = "色温灯" + deviceAddress.substring(0, 4);
							}else{
								return;
							}
						} else if (type == DeviceType.DEVICE_TYPE_SOCKET) {// 转接插座
						//	deviceName = "转接插座" + deviceAddress.substring(0, 4);
							deviceType=parseWireLessType(data);
							if(deviceType==1){
								deviceName = "转接插座" + deviceAddress.substring(0, 4);
							}else{
								return;
							}
						} else if (type == DeviceType.DEVICE_TYPE_CHAZUO) {// 墙壁插座

							deviceType=parseWireLessType(data);
							if(deviceType==8){
								deviceName = "墙壁插座" + deviceAddress.substring(0, 4);
							}else{
								return;
							}
						} else if (type == DeviceType.DEVICE_TYPE_SWITCH) {//电源控制盒
							//deviceName = "电源控制盒" + deviceAddress.substring(0, 4);
							deviceType=parseWireLessType(data);
						    if(deviceType==37){
								deviceName = "电源控制盒" + deviceAddress.substring(0, 4);
							}else{
								return;
							}
						}else if (type == DeviceType.DEVICE_TYPE_CURTAIN) {// 窗帘 DeviceType.DEVICE_TYPE_CURTAIN

							deviceType=parseWireLessType(data);
							if(deviceType==48){
								deviceName = "窗帘" + deviceAddress.substring(0, 4);
							}else{
								return;
							}
                        }else if (type == DeviceType.WIRELSEE_SWITCH_1 ) {// 无线开关
							deviceType=parseWireLessType(data);
							if(deviceType==73){
								deviceName = "无线开关(贴墙式1位)" + deviceAddress.substring(0, 4);

							}else{
								return;
							}
						}else if(type == DeviceType.WIRELSEE_SWITCH_2 ){
							deviceType=parseWireLessType(data);
							if(deviceType==74){
								deviceName = "无线开关(贴墙式2位)" + deviceAddress.substring(0, 4);

							}else{
								return;
							}
						}else if(type == DeviceType.WIRELSEE_SWITCH_3){
							deviceType=parseWireLessType(data);
							if(deviceType==75){
								deviceName = "无线开关(贴墙式3位)" + deviceAddress.substring(0, 4);

							}else{
								return;
							}
						}else if (type == DeviceType.LINGHUO_SWITCH_1 ) {// 无线开关
								deviceType=parseWireLessType(data);
								if(deviceType==97){
									deviceName = "墙壁开关(零火1位)" + deviceAddress.substring(0, 4);

								}else{
									return;
								}
							}else if(type == DeviceType.LINGHUO_SWITCH_2 ){
								deviceType=parseWireLessType(data);
								if(deviceType==98){
									deviceName = "墙壁开关(零火2位)" + deviceAddress.substring(0, 4);

								}else{
									return;
								}
							}else if(type == DeviceType.LINGHUO_SWITCH_3){
							deviceType=parseWireLessType(data);
							if(deviceType==99){
								deviceName = "墙壁开关(零火3位)" + deviceAddress.substring(0, 4);

							}else{
								return;
							}
						}else if(type == DeviceType.DANHUO_SWITCH_1){
							deviceType=parseWireLessType(data);
							if(deviceType==100){
								deviceName = "墙壁开关(单火1位)" + deviceAddress.substring(0, 4);

							}else{
								return;
							}
						}else if(type == DeviceType.DANHUO_SWITCH_2){
							deviceType=parseWireLessType(data);
							if(deviceType==101){
								deviceName = "墙壁开关(单火2位)" + deviceAddress.substring(0, 4);

							}else{
								return;
							}
						}else if(type == DeviceType.DANHUO_SWITCH_3){
							deviceType=parseWireLessType(data);
							if(deviceType==102){
								deviceName = "墙壁开关(单火3位)" + deviceAddress.substring(0, 4);

							}else{
								return;
							}
						}

						Log.i("Tag", "搜索到设备 = " + deviceName);
						boolean bAdd = false;
						int isize = mDeviceList.size();
						for (int i = 0; i < isize; i++) {
							String address = mDeviceList.get(i).getDeviceAddress();
							if (address.equals(deviceAddress)) {
								bAdd = true;
								break;
							}
						}
						// 用来检查以当前搜索用的网关id为mainid的设备中，是否有该彩灯
						// bAdd = DeviceManager.getInstance().checkExist(
						// deviceAddress);
						if (!bAdd) {
							Device devices = new Device();
							devices.setDeviceAddress(deviceAddress);
							devices.setDeviceBrand(deviceAddress);
							devices.setDeviceType(deviceType);
							devices.setDeviceName(deviceName);
							boolean e = false;
							for (int i = 0; i < mDeviceList.size(); i++) {
								if (mDeviceList.get(i).getDeviceAddress().equals(deviceAddress)) {
									e = true;
								}
							}
							if (e) {

							} else {
								mDeviceList.add(devices);
								Message message = Message.obtain();
								message.what = 4;
								mHandler.sendMessage(message);
							}

						}
					}
				}
			});
		}

	}

	private void upLoadDevices(final int i) {
		final Device device = mDeviceList.get(i);
		RequestParams params = new RequestParams(HttpURL.UPLOAD_DEVICE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("deviceAddress", device.getDeviceAddress().toUpperCase());
			obj.put("deviceModel", device.getDeviceBrand());
			obj.put("deviceName", device.getDeviceName());
			obj.put("deviceType", device.getDeviceType() + "");
			Log.e("test", "上传的type" + device.getDeviceType());
			Log.e("test", "上传的type" + device.getDeviceType());
			Log.e("test", "上传的type" + device.getDeviceType());
			obj.put("deviceVersion", "1.0");
			obj.put("deviceWifiSSID", DeviceManager.getInstance().getmWlanBssid());
			obj.put("deviceId", "0");
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("mainDeviceId", DeviceManager.getInstance().getmWlanId());
			switch (type) {
			case DeviceType.DEVICE_TYPE_SOCKET:
				obj.put("productId", "3");
				obj.put("classification", "2");
				break;
			case DeviceType.DEVICE_TYPE_CHAZUO:
				obj.put("productId", "3");
				obj.put("classification", "2");
				break;
			case DeviceType.DEVICE_TYPE_RGB_LIGHT:
				obj.put("productId", "2");
				obj.put("classification", "2");
				break;
			case DeviceType.DEVICE_TYPE_SWITCH:
				obj.put("productId", "6");
				obj.put("classification", "2");
				break;
				case DeviceType.DEVICE_TYPE_CURTAIN:
					obj.put("productId", "48");
					obj.put("classification", "2");
					break;
				case DeviceType.WIRELSEE_SWITCH_1:
					obj.put("productId", "9");
					obj.put("classification", "2");
					break;
				case DeviceType.WIRELSEE_SWITCH_2:
					obj.put("productId", "10");
					obj.put("classification", "2");
					break;
				case DeviceType.WIRELSEE_SWITCH_3:
					obj.put("productId", "11");
					obj.put("classification", "2");
					break;
				case DeviceType.LINGHUO_SWITCH_1:
					obj.put("productId", "9");
					obj.put("classification", "2");
					break;
				case DeviceType.LINGHUO_SWITCH_2:
					obj.put("productId", "10");
					obj.put("classification", "2");
					break;
				case DeviceType.LINGHUO_SWITCH_3:
					obj.put("productId", "11");
					obj.put("classification", "2");
					break;
				case DeviceType.DANHUO_SWITCH_1:
					obj.put("productId", "9");
					obj.put("classification", "2");
					break;
				case DeviceType.DANHUO_SWITCH_2:
					obj.put("productId", "10");
					obj.put("classification", "2");
					break;
				case DeviceType.DANHUO_SWITCH_3:
					obj.put("productId", "11");
					obj.put("classification", "2");
					break;
			default:
				break;
			}
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("Tag", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("Tag", result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						String deviceId = jo.getString("data");
						Message msg = Message.obtain();
						msg.what = 1;
						msg.arg1 = i;
						mHandler.sendMessage(msg);
					} else {
						String deviceId = jo.getString("data");
						Message msg = Message.obtain();
						msg.what = 2;
						msg.obj = device.getDeviceName() + "已被绑定";
						mHandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void initData() {
		// showSearchDialog(10 * 1000);
		searching = true;
		// if (!rippleBackground.isRippleAnimationRunning()) {
		// rippleBackground.startRippleAnimation();
		// }
//		if (!mSVProgressHUD.isShowing()) {
		mSVProgressHUD1.showWithStatusAndMaskType("正在搜索", SVProgressHUDMaskType.BlackCancel);
//			mSVProgressHUD.showWithStatus("正在搜索");
			
//		}
		serachLightDevice();
//		new Thread(new Runnable() {
//
//			@Override
//			public void run() {
//				try {
//					Thread.sleep(20 * 1000);
//					isSearching = false;
//				} catch (InterruptedException e) {
//
//					e.printStackTrace();
//				}
//				boolean is = false;
//				if (is) {
//
//				} else {
//					Message msg = Message.obtain();
//					msg.what = 0;
//					msg.arg1 = 0;
//					mHandler.sendMessage(msg);
//				}
//			}
//		}).start();
	}

	private void serachLightDevice() {
//		sendCmdTimes = 0;
		isSearching = true;
		socket.setNotReceiving(false);
		new Thread(new Runnable() {

			@Override
			public void run() {
//				while (sendCmdTimes < 20) {
				while (searching) {
					try {
						socket.sendMqttData(searchCmd);
//						sendCmdTimes++;
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);
		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	private String parseData(String data) {
		Log.i("wmy", "解析红外设备地址 = " + data);
		String deviceAddress = "";
		try {
			JSONObject jo = new JSONObject(data);
			String g = jo.getString("g");
			JSONObject jo1 = new JSONObject(g);

			JSONArray ja = jo1.getJSONArray("data");
			int[] add = new int[5];
			for (int i = 1; i < 6; i++) {
				add[i - 1] = ja.getInt(i);
			}
			for (int i = 0; i < add.length; i++) {
				if (Integer.toHexString(add[i]).length() == 1) {
					deviceAddress = deviceAddress + "0" + Integer.toHexString(add[i]);
				} else {
					deviceAddress = deviceAddress + Integer.toHexString(add[i]);
				}
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return deviceAddress;
	}


	private int parseWireLessType(String data) {
		Log.i("wmy", "解析红外设备地址 = " + data);
		int type = 73;
		try {
			JSONObject jo = new JSONObject(data);
			String g = jo.getString("g");
			JSONObject jo1 = new JSONObject(g);
			JSONArray ja = jo1.getJSONArray("data");
			int[] add = new int[5];
			for (int i = 1; i < 6; i++) {
				type = ja.getInt(5);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return type;
	}

	private void saveLight1() {
		mSVProgressHUD = new SVProgressHUD(this);
		mSVProgressHUD.showWithStatus("正在提交");
		int isize = mDeviceList.size();
		if (isize > 0) {
			mUpLoadCounts = 0;
			upLoadDevices(mUpLoadCounts);
		} else {

		}
	}

}